
var api = require('../../api.js');
var app = getApp();
var share_count = 0;
Page({
    data: {
       imgServer :  api.default.img_server,
      x:wx.getSystemInfoSync().windowWidth,
      y:wx.getSystemInfoSync().windowHeight,
      //content:{},//
      banner_list:[],//banner图数组
      brandlist:[],
      hotProductList:[],
      newProductList:[],
      depotList:[],//仓库列表
      currentDepot:null,//当前的仓库信息 {id:23，name:'tgd'}
      productCate:[],//推荐产品分类
      isFixed:false,//仓库是否固定
      popupShow:false,//首页弹出框是否显示
      popContent:{},//设置的弹出框
      timeData: {},//倒计时
      moneyIcon:api.MONEYICON,
      moneyIconOther:api.MONEYICONOTHER,
      keyword:"",//头部的搜索内容
      goods_list:[],//底部的商品列表
      params:{
        pageNum:1,
        pageSize:10,
        depotId:0,
      },
      isContinue:true,//是否继续加载更多
      resourcesList:[],//精选活动
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var page = this;  
       
        page.getHomeDepot();
        console.log(options);
        if(options.scene){
            let queryarr=decodeURIComponent(options.scene).split("&")
            let urlobj={};
            queryarr.map(item=>{
              let left = item.split('=')[0];
              let right = item.split('=')[1];
              urlobj[left] = right
            })
            //let id = urlobj.oId;
            let share_code = urlobj.dCode;
           // options.id=id;
            options.share_code =share_code;
          }
        if(options.share_code){
            let token = wx.getStorageSync("token");
            if (!token) {
              wx.setStorage({
                key: "share_code",
                data: options.share_code
              })
            } else {
              app.bindSalesInfo(options.share_code);
            }
        }
    },
    getBtmList(){
        let page = this;
        app.request({
            url:api.default.getHomeBtmList,
            method:'POST',
            data:page.data.params,
            success(res){
                if(res.code ==200 && res.data && res.data.length>0){
                    res.data.map(item=>{
                        if(item.tips){
                            item.tips = item.tips.split(',')
                        }
                    })
                    page.setData({
                        goods_list:[...page.data.goods_list,...res.data],
                        'params.pageNum':page.data.params.pageNum+1
                    })
                }else{
                    page.setData({
                        isContinue:false
                    })
                }
            }
        })
    },
    inputConfirm: function (e) {
        var page = this;
        var keyword = e.detail;
        if (keyword.length == 0)
            return;
        page.setData({
            keyword: keyword,
        });
        wx.navigateTo({
          url: '/pages/search/search?searchVal=' + keyword,
        })
    },
    searchCancel: function () {
        // wx.navigateBack({
        //     delta: 1,
        // });
        var page = this;
        var keyword = "";

        page.setData({
            page: 1,
            keyword: keyword,
            goods_list:[],
            show_result:false,
            show_history:true,
            history_list: page.getHistoryList(true),
        });

    },
    getHomeDepot(){
        let page = this;
        app.request({
            url: api.default.homeDepotList,
            success:function(res){
                if(res.code ==200 && res.data){
                    let tempdepotList = res.data;
                    let tempcurrentDepot = null;
                    for(let depot of tempdepotList){
                        if(depot.default){
                            tempcurrentDepot = depot;
                            break
                        }
                    };
                    page.setData({
                        currentDepot: tempcurrentDepot,
                        depotList:tempdepotList,
                        'params.depotId':tempcurrentDepot.id
                    })
                    page.loadData();
                    page.getBtmList();
                }
            }
          })
    },
    onTabChange(e){
        //e.detail: {index: 1, name: 24, title: "3"}
        let id = e.detail.name;
        let name = e.detail.title;
        let newObj ={id:id,name:name}
        this.setData({
            currentDepot: newObj
        });
        this.loadData();
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
          })
    },
    /**
     * 加载页面数据
     */
    loadData: function () {
        var page = this;
        app.request({
            url: api.default.homeContent,
            data:{
                'depotId': page.data.currentDepot.id,
            },
            success: function (res) {
              if (res.code == 200) {
                //page.setData(res.data);
                let data = res.data;
                let len = data.homeRecommandBlocks.length;
                for(let i=0; i<len;i++){
                    let len2 = data.homeRecommandBlocks[i].productList && data.homeRecommandBlocks[i].productList.length;
                    if(len2 >0){
                        for(let j=0;j<len2;j++){
                            data.homeRecommandBlocks[i].productList[j].index = j
                        }
                    }
                }
                let flash = null;
                if(data.homeFlashPromotion.flashPromotionProductSessions && data.homeFlashPromotion.flashPromotionProductSessions.length>0){
                    flash = data.homeFlashPromotion.flashPromotionProductSessions[0];
                    let now = new Date(data.systemTime);
                    let year = now.getFullYear();
                    let month = now.getMonth()+1;
                    let date = now.getDate();
                    // year + '-' + (month  < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date);
                  //let endTimeStr = year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)+" "+ flash.endTime;

                  let hour = flash.endTime.split(":")[0];
                  let minute = flash.endTime.split(":")[1];
                  let second = flash.endTime.split(":")[2];
                  let endTime = new Date(year, month, date, hour, minute, second).getTime();
                  // let textTime = new Date(2018, 7, 14, 18, 55, 49);
                  // console.log("测试1111：" + textTime)
                    let interval = endTime-now.getTime();
                    flash.interval = parseInt(interval);
                }
                page.setData({
                  bannerlist: data.advertiseList,
                  //brandlist: data.brandList,
                  //hotProductList:data.hotProductList,
                  //newProductList: data.newProductList,
                  flashInfo: flash,
                  homeRecommandBlocks:data.homeRecommandBlocks,//最下面的promotion list
                  homeProductCategories:data.homeProductCategories,//产品分类
                  homePromotion:data.homePromotion,//活动版块
                  resourcesList:data.resourcesList?data.resourcesList:[],//精选活动
                })
              }else{
                  wx.showToast({
                    title: res.message,
                    icon:"none"
                  })
              }
            },
            fail:function(res){
                wx.showToast({
                    title: res.message,
                    icon:"none"
                })
            },
            complete: function () {
              wx.stopPullDownRefresh();
            }
          });
    },
    onCountDown(e){
      this.setData({
        timeData: e.detail
      });
      let { hours, minutes, seconds } = e.detail
      if (hours == 0 && minutes == 0 && seconds == 0) {
        this.setData({
          'flashInfo.flashPromotionProducts': [],//当前时间段的秒杀结束 
        })
      }
    },
  redirectToList:function(e){
    let type= e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/list/list?type=' + type,
    })
  } ,
  toBrandList(){
    wx.navigateTo({
      url: '/pages/brand/list',
    })
  },
     /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        share_count = 0;
        this.getPopContent();//首页的弹窗
        let token = wx.getStorageSync('token');
        if(token){
            app.checkUserIditity();//更新用户的角色
        }
    },
    getPopContent(){
        var page = this;
        app.request({
            url: api.default.getHomePop,
            success: function (res) {
              if (res.code == 200 && res.data.length>0) {
                let data = res.data[0];
                let type = data.ruleType;
                if(type == 1){   //只弹出1次
                    let curStorKeys= wx.getStorageInfoSync().keys;//目前storage里存在的
                    let sKey="homePop"+type;//将要存的数据的key值
                    if(!curStorKeys.includes(sKey)){
                        page.setData({
                            popContent:data,
                            popupShow:true
                        });
                        wx.setStorageSync(sKey, true)
                    }
                }else if(type == 2){ //每天弹出1次
                    let curStorKeys= wx.getStorageInfoSync().keys;//目前storage里存在的
                    let sKey="homePop"+type;//将要存的数据的key值
                    let curStorInfo= wx.getStorageSync(sKey);
                    let isShow= false;
                    if(curStorInfo){
                        console.log(curStorInfo)
                        let time = new Date();
                        let interval = time.getTime() - curStorInfo;
                        isShow = interval-86400000>0? true: false;
                    }
                    
                    if(!curStorKeys.includes(sKey) ||isShow){
                        page.setData({
                            popContent:data,
                            popupShow:true
                        });
                        let curTime = new Date().getTime();
                        wx.setStorageSync(sKey, curTime)
                    }
                }else{  //打开就弹
                    page.setData({
                        popContent:data,
                        popupShow:true
                    });
                }
                    
              }
            }
        })
    },
    toPromotionDetail(e){
        let detillist = e.currentTarget.dataset.detillist;
        if(!detillist || detillist.length < 1) return;
        let item = detillist[0];
        this.redirectActivity(null,item);
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.loadData();
        setTimeout(()=>{
            wx.stopPullDownRefresh();
        },1000 )
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function () {
        if(this.data.isContinue){
            this.getBtmList();
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (options) {
        var page = this;
        let share_code = wx.getStorageSync("user_sharecode") || '';//经销商（自己）的分享码
        //let shareImgUrl = page.data.subImages[0];
        var res = {
            path: "/pages/index/index?share_code=" + share_code,
            title: '东京生活馆药妆 欢迎您的到来~',
            imageUrl: '/images/logo.jpeg',
        };
        return res;
    },
    receive: function (e) {
        var page = this;
        var id = e.target.dataset.index;
        wx.showLoading({
            mask: true,
        });
        if (!page.hideGetCoupon) {
            page.hideGetCoupon = function (e) {
                var url = e.currentTarget.dataset.url || false;
                page.setData({
                    get_coupon_list: null,
                });
                if (url) {
                    wx.navigateTo({
                        url: url,
                    });
                }
            };
        }
        app.request({
            url: api.coupon.receive,
            data: {id: id},
            success: function (res) {
                wx.hideLoading();
                if (res.code == 200) {
                    page.setData({
                        get_coupon_list: res.data.list,
                        coupon_list: res.data.coupon_list
                    });
                } else {
                    wx.showToast({
                        title: '已领取',
                        duration: 2000
                    })
                    page.setData({
                        coupon_list: res.data.coupon_list
                    });
                }
            },
            // complete: function () {
            //   wx.hideLoading();
            // }
        });
    },
    clsoePop(){
        let page = this;
        page.setData({
            popupShow:false
        })
    },
    navigatorClick: function (e) {
        var page = this;
        var open_type = e.currentTarget.dataset.open_type;
        var url = e.currentTarget.dataset.url;
        if (open_type != 'wxapp')
            return true;
        //console.log(url);
        url = parseQueryString(url);
        url.path = url.path ? decodeURIComponent(url.path) : "";
        console.log("Open New App");
        wx.navigateToMiniProgram({
            appId: url.appId,
            path: url.path,
            complete: function (e) {
                console.log(e);
            }
        });
        return false;

        function parseQueryString(url) {
            var reg_url = /^[^\?]+\?([\w\W]+)$/,
                reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
                arr_url = reg_url.exec(url),
                ret = {};
            if (arr_url && arr_url[1]) {
                var str_para = arr_url[1], result;
                while ((result = reg_para.exec(str_para)) != null) {
                    ret[result[1]] = result[2];
                }
            }
            return ret;
        }
    },
    closeCouponBox: function (e) {
      this.setData({
        get_coupon_list: ""
      });
    },
    redirectActivity(e,item){
        let type = e?e.currentTarget.dataset.redirecttype : item.type;
        let h5url = e?e.currentTarget.dataset.h5url : item.redirectUrl;
        let pid = e?e.currentTarget.dataset.productid : item.productId;
        let rid = e?e.currentTarget.dataset.rid : item.id;
        let subjectid = e?e.currentTarget.dataset.subject : item.subjectId;

        let finalUrl = '';
        if(type ==1){// 1,产品详情  2,专题列表页 3,产品分类列表页 4, H5
            finalUrl = '/pages/goods/goods?id='+ pid;
        }else if(type == 2){
            finalUrl = '/pages/block/block?bid='+subjectid
        }else if (type ==3){
            
            finalUrl = e? '/pages/resource/product?rid='+rid : '/pages/promotion/promotion?pid='+rid;
        }else{
            // finalUrl = '/pages/xinren/baoyou/baoyou?htmlUrl='+h5url
            wx.setStorageSync('html', h5url)
            finalUrl = '/pages/activity/detail';
        }
        wx.navigateTo({
          url: finalUrl,
        })
    },
    bannerRedirect(e){
        let type = e?e.currentTarget.dataset.redirecttype : item.type;
        let h5url = e?e.currentTarget.dataset.h5url : item.redirectUrl;
        let pid = e?e.currentTarget.dataset.productid : item.productId;
        let rid = e?e.currentTarget.dataset.rid : item.id;
        let subjectid = e?e.currentTarget.dataset.subject : item.subjectId;

        let finalUrl = '';
        if(type ==1){// 1,产品详情  2,专题列表页 3,产品分类列表页 4, H5
            finalUrl = '/pages/goods/goods?id='+ pid;
        }else if(type == 2){
            finalUrl = '/pages/block/block?bid='+subjectid
        }else if (type ==3){
            finalUrl =  '/pages/resource/product?rid='+rid+'&isFromBanner=true';
        }else{
            // finalUrl = '/pages/xinren/baoyou/baoyou?htmlUrl='+h5url
            wx.setStorageSync('html', h5url)
            finalUrl = '/pages/activity/detail';
        }
        wx.navigateTo({
          url: finalUrl,
        })
    },
});
